package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class EmployeeRealm extends AuthorizingRealm {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    public String getName() {
        return super.getName();
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //根据角色信息查询角色信息和权限信息
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        if(employee.isAdmin()){
            info.addRole("admin");
            info.addStringPermission("*:*");
            return info;
        }
        //查询角色的编号
        Set<String> roleSn = employeeService.getRoleByEmpId(employee.getId());
        //查询权限表达式
        Set<String> resource = employeeService.getPermissionByEmpId(employee.getId());
        info.setStringPermissions(resource);
        info.setRoles(roleSn);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Employee emp = employeeService.getByUsername(username);
        if (emp == null) {
            return null;
        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(emp, emp.getPassword(), ByteSource.Util.bytes("admin"), getName());
        return info;
    }

    //清除缓存
    public void clearCached(){
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }


}
